package com.py.credit.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

/**
 * 文件处理工具类
 * 
 * @author Leegern
 * @date 2018年3月6日
 */
public class FileUtils {

	/** 字符集：UTF-8 **/
	public static final String CHARSET_UTF8 = "UTF-8";

	/** 文件后缀名：word **/
	public static final String SUFFIX_WORD = ".docx";

	/** 文件分隔符 **/
	public static final String FILE_SEPARATOR = "/";

	/**
	 * 获取web应用根目录路径
	 * 
	 * @return
	 */
	public static String getWebRootPath() {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (null == classLoader) {
			classLoader = ClassLoader.getSystemClassLoader();
		}
		java.net.URL url = classLoader.getResource("");
		String rootClassPath = url.getPath() + FILE_SEPARATOR;
		File rootFile = new File(rootClassPath);
		String webInfoPath = rootFile.getParent() + FILE_SEPARATOR;
		File webInfoDir = new File(webInfoPath);
		String webRootPath = webInfoDir.getParent() + FILE_SEPARATOR;
		return webRootPath;
	}

	/**
	 * 流输出
	 * 
	 * @param is
	 *            输入流
	 * @param os
	 *            输出流
	 * @throws IOException
	 */
	public static void pushStream(InputStream is, OutputStream os) throws IOException {
		byte[] bytes = new byte[1024];
		int len = 0;
		try {
			while ((len = is.read(bytes)) > 0) {
				os.write(bytes, 0, len);
			}
			os.flush();
		} finally {
			if (null != is)
				is.close();
			if (null != os)
				os.close();
		}
	}

	public static boolean downloadFile(String path, HttpServletResponse response) {
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			// String ext = filename.substring(filename.lastIndexOf(".") +
			// 1).toUpperCase();

			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			String codedFileName = URLEncoder.encode(filename, "UTF-8");
			response.addHeader("Content-Disposition", "attachment;filename=" + codedFileName);
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			response.setContentType("text/html; charset=utf-8");
			try {
				PrintWriter writer = response.getWriter();
				writer.write("该文件找不到！");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
			ex.printStackTrace();
			return false;

		}
		return true;
	}
	
	      /*
	      * @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip
	      * @param resourePath 源文件/文件夹
	      * @param targetPath  目的压缩文件保存路径
	      * @return void
	      * @throws Exception 
	      */
	     public static void compressedFile(String resourcesPath,String targetPath) throws Exception{
	         File resourcesFile = new File(resourcesPath);     //源文件
	         File targetFile = new File(targetPath);           //目的
	         //如果目的路径不存在，则新建
	        if(!targetFile.exists()){     
	             targetFile.mkdirs();  
	         }
	         
	         String targetName = resourcesFile.getName()+".zip";   //目的压缩文件名
	         FileOutputStream outputStream = new FileOutputStream(targetPath+File.separator+targetName);
	         ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));
	         
	         createCompressedFile(out, resourcesFile, "");
	         
	        out.close();  
	     }
	     
	      /**
	       * @desc 生成压缩文件。
	       *                  如果是文件夹，则使用递归，进行文件遍历、压缩
	       *       如果是文件，直接压缩
	       * @param out  输出流
	       * @param file  目标文件
	       * @return void
	       * @throws Exception 
	       */
	       public static void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{
	          //如果当前的是文件夹，则进行进一步处理
	          if(file.isDirectory()){
	              //得到文件列表信息
	              File[] files = file.listFiles();
	              //将文件夹添加到下一级打包目录
	              out.putNextEntry(new ZipEntry(dir+"/"));
	                  
	              dir = dir.length() == 0 ? "" : dir +"/";
	                  
	              //循环将文件夹中的文件打包
	              for(int i = 0 ; i < files.length ; i++){
	                   createCompressedFile(out, files[i], dir + files[i].getName());         //递归处理
	              }
	           }else{   //当前的是文件，打包处理
	               //文件输入流
	               FileInputStream fis = new FileInputStream(file);
	                  
	               out.putNextEntry(new ZipEntry(dir));
	               //进行写操作
	               int j =  0;
	               byte[] buffer = new byte[1024];
	               while((j = fis.read(buffer)) > 0){
	                    out.write(buffer,0,j);
	               }
	               //关闭输入流
	               fis.close();
	           }
	       }
	       
	       /**
		       * @desc 删除指定文件夹下的所有文件
		       * @param out  输出流
		       * @param file  目标文件
		       * @return void
		       * @throws Exception 
		       */

	       public static boolean delAllFile(String path) {  
	              boolean flag = false;  
	              File file = new File(path);  
	              if (!file.exists()) {  
	                return flag;  
	              }  
	              if (!file.isDirectory()) {  
	                return flag;  
	              }  
	              String[] tempList = file.list();  
	              File temp = null;  
	              for (int i = 0; i < tempList.length; i++) {  
	                 if (path.endsWith(File.separator)) {  
	                    temp = new File(path + tempList[i]);  
	                 } else {  
	                     temp = new File(path + File.separator + tempList[i]);  
	                 }  
	                 if (temp.isFile()) {  
	                    temp.delete();  
	                 }  
	                 if (temp.isDirectory()) {  
	                    delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件  
	                    delFolder(path + "/" + tempList[i]);//再删除空文件夹  
	                    flag = true;  
	                 }  
	              }  
	              return flag;  
	            }  
	       
	          
	         /**
		       * @desc 删除文件夹 
		       * @param out  输出流
		       * @param file  目标文件
		       * @return void
		       * @throws Exception 
		     */

	          public static void delFolder(String folderPath) {  
	    	   try {  
	    	        delAllFile(folderPath); //删除完里面所有内容  
	    	        String filePath = folderPath;  
	    	        filePath = filePath.toString();  
	    	        java.io.File myFilePath = new java.io.File(filePath);  
	    	        myFilePath.delete(); //删除空文件夹  
	    	     } catch (Exception e) {  
	    	       e.printStackTrace();   
	    	     }  
	    	  }  

	         
	       public static void main(String[] args){
	    	   try {
	    	       FileUtils.compressedFile("C:\\sgs\\reports\\M0120181219027", "C:\\sgs\\reportsZip");
	    	       System.out.println("压缩文件已经生成...");
	    	   } catch (Exception e) {
	    	       System.out.println("压缩文件生成失败...");
	    	       e.printStackTrace();
	    	   }
	      } 
}